/**
 * 营养相关的工具函数
 */

/**
 * 计算用户的营养素缺口
 * @param {Object} userTarget - 用户营养目标
 * @param {Object} currentIntake - 当前已摄入的营养素
 * @returns {Object} - 返回各营养素的缺口
 */
exports.calculateNutritionDeficit = (userTarget, currentIntake) => {
  // 设置默认值，确保即使某些字段不存在也不会出错
  const target = {
    calories: userTarget.calories || 2000,
    carbs: userTarget.carbs || 250,
    protein: userTarget.protein || 75,
    fat: userTarget.fat || 65,
    fiber: userTarget.fiber || 25
  };
  
  const intake = {
    calories: currentIntake.calories || 0,
    carbs: currentIntake.carbs || 0,
    protein: currentIntake.protein || 0,
    fat: currentIntake.fat || 0,
    fiber: currentIntake.fiber || 0
  };
  
  // 计算缺口并确保不为负数
  return {
    calories: Math.max(0, target.calories - intake.calories),
    carbs: Math.max(0, target.carbs - intake.carbs),
    protein: Math.max(0, target.protein - intake.protein),
    fat: Math.max(0, target.fat - intake.fat),
    fiber: Math.max(0, target.fiber - intake.fiber)
  };
};

/**
 * 计算食物的推荐份量
 * @param {Object} food - 食物对象，包含营养成分
 * @param {Object} nutritionDeficit - 营养素缺口
 * @param {string} primaryNutrient - 主要考虑的营养素
 * @returns {Object} - 返回推荐份量及相关信息
 */
exports.calculateRecommendedPortion = (food, nutritionDeficit, primaryNutrient = 'calories') => {
  // 获取食物的营养素含量
  const nutrition = food.nutrition || {};
  
  // 默认份量(克)
  let defaultPortion = 100;
  
  // 根据主要营养素计算推荐份量
  let recommendedPortion = defaultPortion;
  let nutrientProvided = 0;
  
  // 确保营养素值存在且大于0
  const nutrientContent = parseFloat(nutrition[primaryNutrient]) || 0;
  if (nutrientContent > 0 && nutritionDeficit[primaryNutrient] > 0) {
    // 计算需要多少克食物才能满足30%的营养素缺口
    const deficit = nutritionDeficit[primaryNutrient];
    const portionForThirtyPercent = (deficit * 0.3) / (nutrientContent / 100);
    
    // 限制在合理范围内
    recommendedPortion = Math.min(Math.max(portionForThirtyPercent, 50), 300);
    nutrientProvided = (nutrientContent * recommendedPortion) / 100;
  }
  
  // 计算提供的各种营养素
  const providedNutrition = {};
  for (const [nutrient, value] of Object.entries(nutrition)) {
    if (typeof value === 'number' || !isNaN(parseFloat(value))) {
      providedNutrition[nutrient] = (parseFloat(value) * recommendedPortion) / 100;
    }
  }
  
  return {
    recommendedPortion: Math.round(recommendedPortion), // 四舍五入到整数
    primaryNutrientProvided: nutrientProvided,
    providedNutrition,
    percentOfDeficit: nutritionDeficit[primaryNutrient] > 0 
      ? (nutrientProvided / nutritionDeficit[primaryNutrient]) * 100 
      : 0
  };
};

/**
 * 生成食物的营养和健康标签
 * @param {Object} food - 食物对象
 * @param {number} giValue - GI值(可选)
 * @returns {Array} - 返回一组标签
 */
exports.generateFoodTags = (food, giValue = null) => {
  const tags = [];
  const nutrition = food.nutrition || {};
  
  // GI值相关标签
  if (giValue !== null) {
    if (giValue <= 55) {
      tags.push('低GI值');
      tags.push('血糖上升缓慢');
    } else if (giValue <= 69) {
      tags.push('中等GI值');
    } else {
      tags.push('高GI值');
    }
  }
  
  // 营养素相关标签
  const protein = parseFloat(nutrition.protein) || 0;
  const fat = parseFloat(nutrition.fat) || 0;
  const carbs = parseFloat(nutrition.carbs) || parseFloat(nutrition.carbohydrate) || 0;
  const fiber = parseFloat(nutrition.fiber) || 0;
  const calories = parseFloat(nutrition.calories) || 0;
  
  if (protein > 15) tags.push('高蛋白');
  if (protein > 20 && fat < 10) tags.push('优质蛋白来源');
  if (fiber > 5) tags.push('高纤维');
  if (fat < 3) tags.push('低脂肪');
  if (carbs < 10) tags.push('低碳水');
  
  // 营养密度
  if (calories > 0 && protein / calories > 0.1) {
    tags.push('高营养密度');
  }
  
  // 糖尿病友好标签
  if ((giValue !== null && giValue <= 55) || carbs < 15) {
    tags.push('糖尿病友好');
  }
  
  return tags;
};

/**
 * 生成食物推荐理由
 * @param {Object} food - 食物对象
 * @param {Object} nutritionDeficit - 营养素缺口
 * @param {number} giValue - GI值(可选)
 * @returns {Array} - 返回推荐理由数组
 */
exports.generateRecommendationReasons = (food, nutritionDeficit, giValue = null) => {
  const reasons = [];
  const nutrition = food.nutrition || {};
  
  // 基于营养缺口的推荐理由
  if (nutritionDeficit.protein > 20 && parseFloat(nutrition.protein) > 10) {
    reasons.push('补充您所需的蛋白质');
  }
  
  if (nutritionDeficit.fiber > 10 && parseFloat(nutrition.fiber) > 3) {
    reasons.push('增加膳食纤维摄入');
  }
  
  if (nutritionDeficit.calories > 500 && parseFloat(nutrition.calories) > 100) {
    reasons.push('提供所需能量');
  }
  
  // 基于GI值的推荐理由
  if (giValue !== null) {
    if (giValue <= 55) {
      reasons.push('低GI值食物，有助于控制血糖');
    } else if (giValue <= 69) {
      reasons.push('中等GI值，适量食用');
    }
  }
  
  // 基于食物类型的推荐理由
  const category = food.category;
  if (category) {
    if (category.includes('蔬菜') || category === 'vegetables') {
      reasons.push('增加蔬菜摄入，提供维生素和抗氧化物');
    }
    
    if (category.includes('全谷物') || category === 'grains' && giValue && giValue <= 55) {
      reasons.push('全谷物含有更多膳食纤维和营养素');
    }
    
    if (category.includes('蛋白质') || category === 'protein') {
      reasons.push('优质蛋白质来源，有助于肌肉维护');
    }
  }
  
  // 确保至少有一个推荐理由
  if (reasons.length === 0) {
    reasons.push('均衡营养摄入');
  }
  
  return reasons;
};

/**
 * 根据用户的营养素缺口生成个性化饮食建议
 * @param {Object} nutritionDeficit - 营养素缺口
 * @returns {Array} - 返回饮食建议数组
 */
exports.generateDietarySuggestions = (nutritionDeficit) => {
  const suggestions = [];
  
  // 添加通用建议
  suggestions.push({
    type: 'general',
    content: '保持食物多样性，平衡摄入各类营养素'
  });
  
  suggestions.push({
    type: 'meal_order',
    content: '建议先吃蔬菜和蛋白质食物，最后吃主食，有助于控制餐后血糖波动'
  });
  
  // 根据营养缺口添加特定建议
  if (nutritionDeficit.protein > 30) {
    suggestions.push({
      type: 'nutrient_specific',
      content: '您当前蛋白质摄入不足，建议增加鱼、禽、蛋、豆制品等优质蛋白来源'
    });
  }
  
  if (nutritionDeficit.fiber > 15) {
    suggestions.push({
      type: 'nutrient_specific',
      content: '您的膳食纤维摄入不足，多吃蔬菜、全谷物和豆类食物'
    });
  }
  
  if (nutritionDeficit.calories > 500) {
    suggestions.push({
      type: 'nutrient_specific',
      content: '您今日能量摄入较少，请确保摄入足够的食物量以满足身体需求'
    });
  } else if (nutritionDeficit.calories < 100) {
    suggestions.push({
      type: 'nutrient_specific',
      content: '您已接近能量目标，接下来的餐食请控制总量'
    });
  }
  
  return suggestions;
}; 